package ua.maxicash.controller;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import ua.maxicash.service.EmployerService;
import ua.maxicash.service.WorkerService;
import ua.maxicash.vo.Employer;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

@Controller
@RequestMapping("/employers")
public class EmployerController {

    private static final Logger logger = Logger.getLogger(EmployerController.class);

    @Autowired
    private EmployerService employerService;

    @Autowired
    private WorkerService workerService;

    @RequestMapping(value = "/{idEmployer}", method = RequestMethod.GET)
    public String showEmployersPage(@PathVariable Long idEmployer, Model model) {

        Employer employer = employerService.getEmployerById(idEmployer);

        if (employer!=null) {
            model.addAttribute("employer", employer);
            return "employer";
        } else {
            return "error";
        }
    }


    @RequestMapping(value = "{idEmployer}/getImage", method = RequestMethod.GET)
    public void showEmployersImage(@PathVariable Long idEmployer,
                                   HttpServletResponse resp) {

        Employer employer = employerService.getEmployerById(idEmployer);

        int nextInt;

        resp.setContentType("image/png");
        try {
            if (employer.getAvatar() != null) {
                resp.getOutputStream().write(employer.getAvatar());
            } else {
                InputStream in = this.getClass().getClassLoader().getResourceAsStream("noAvatar.jpg");
                OutputStream out = resp.getOutputStream();
                int next;
                while ((next = in.read()) != -1)
                    out.write(next);
            }
            resp.getOutputStream().flush();
            resp.getOutputStream().close();
        } catch (IOException e) {
            logger.error(e);
        }

    }

    @RequestMapping(method = RequestMethod.GET)
    public String showListOfEmployers(Model model) {

        model.addAttribute("employers", employerService.listEmployer());

        return "listOfEmployers";
    }

}
